package com.hulk.rpc.registry;

import com.google.common.base.Preconditions;
import com.hulk.rpc.config.common.HostPort;
import com.hulk.rpc.exception.HulkRpcException;
import com.hulk.rpc.registry.impl.local.LocalRegistry;
import com.hulk.rpc.registry.impl.zk.ZooKeeperRegister;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.io.Closeable;
import java.util.List;

/**
 * 服务注册管理器
 *
 * @author xuxukang
 * @date 2019-03-09 09:10
 */
public interface ServerRegistry extends Closeable {

  /**
   * 一般为初始化连接注册中心的client(list是因为分布式)
   *
   * @param hostPorts 自定义注册中心地址、开源注册中心地址(zk、consul)
   */
  void init(List<HostPort> hostPorts);

  /**
   * 注册单个服务(需要判断唯一性)
   *
   * @param serverMetaInfo 要注册的服务的元数据
   */
  void register(ServerMetaInfo serverMetaInfo);

  /**
   * @param serverMetaInfo 服务元数据
   */
  void unregister(ServerMetaInfo serverMetaInfo);

  @Getter
  @AllArgsConstructor
  enum ServerRegistryEnum {
    /**
     * 注册中心工厂
     */
    local(LocalRegistry.class),
    zookeeper(ZooKeeperRegister.class);

    private Class<? extends ServerRegistry> aClass;

    public ServerRegistry getServerRegistry() {
      try {
        return this.aClass.getDeclaredConstructor().newInstance();
      } catch (Exception e) {
        throw new HulkRpcException("反射获取服务注册器失败", e);
      }
    }

    public static ServerRegistryEnum match(String name, ServerRegistryEnum defaultRegistry) {
      Preconditions.checkState(StringUtils.isNotBlank(name));

      for (ServerRegistryEnum value : ServerRegistryEnum.values()) {
        if (value.name().equalsIgnoreCase(name)) {
          return value;
        }
      }
      return defaultRegistry;
    }
  }

}
